var ztree_user, ztree_role, ztree_func;
var userStatus = true, roleStatus = true, funcStatus = true; //默认正常状态， flase 置灰色
var isFirst = true; // 给叶节点加图标，只在第一次加载，避免图片重复

$(function () {
    $(".btn-add").on("click", addSave);
    $(".btn-delete").on("click", deleteSave);
    $(".btn-reset").on("click", resetAllTree);
    $("#btnFuncSearch").on("click", funcSearch);
    $("#btnRoleSearch").on("click", roleSearch);
    $("#btnUserSearch").on("click", userSearch);

    initAllTree();

    // 初始化ztree高度
    initZtreeBox();

    $(window).resize(function (event) {
        // 初始化ztree高度
        initZtreeBox();
    });
});

/**
 * 初始化ztree高度
 */
function initZtreeBox() {
    var h = $(window).height(),
        bh = $(".oper-box").outerHeight(),
        t = $(".ztree").offset().top;
    h = h - bh - t - 31;
    $(".ztree").height(h);
}

function initAllTree() {
    var url = '/manage/auth/allurf';
    Base.ajax({
        url: url,
        success: function (data) {
            data = data.data;
            if (null != data.funcs) {
                funcTreeData = data.funcs;
                initFunc(funcTreeData, funcStatus);
            }
            if (null != data.users) {
                userTreeData = data.users;
                initUser(userTreeData, userStatus);
            }
            if (null != data.roles) {
                roleTreeData = data.roles;
                initRole(roleTreeData, roleStatus);
            }
            isFirst = false;
        }
    });
}

function initUser(data, status) {
    var zNodes = data;
    if (isFirst) {
        for (var i = zNodes.length - 1; i >= 0; i--) {
            var z = zNodes[i];
            if (z.type == "user") {
                z.name = '<i class="iconfont icon-yonghu"></i> ' + z.name;
                z.name = z.name + " [" + z.id + "]";
            }
        }
        ;
    }

    var setting = {
        view: {
            showIcon: false,
            nameIsHTML: true,
            showTitle: false,
            showLine: false,
            fontCss: function (treeId, treeNode) {
                var o = {};
                if (treeNode.highlight) {
                    o = {
                        color: "red",
                        "font-weight": "bold"
                    };
                } else if (!status) {
                    o = {
                        color: "#bbb",
                        "font-weight": "bold"
                    };
                } else {
                    o = {
                        color: "#32b5cb",
                        "font-weight": "bold"
                    };
                }

                return o;
            }
        },
        check: {
            enable: true,
            chkboxType: {
                "Y": "s",
                "N": "ps"
            }
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: chooseUserTreeStatus,
            beforeClick: function (event, treeId, treeNode) {
                return false;
            }
        }
    };

    ztree_user = $.fn.zTree.init($("#userTree"), setting, zNodes);
}

function initRole(data, status) {
    var zNodes = data;
    if (isFirst) {
        for (var i = zNodes.length - 1; i >= 0; i--) {
            var z = zNodes[i];
            if (z.type == "role") {
                z.name = '<i class="iconfont icon-shejishi"></i> ' + z.name;
                z.name = z.name + " [" + z.id + "]";
            }
        }
    }
    var setting = {
        view: {
            showIcon: false,
            nameIsHTML: true,
            showTitle: false,
            showLine: false,
            fontCss: function (treeId, treeNode) {
                var o = {};
                if (treeNode.highlight) {
                    o = {
                        color: "red",
                        "font-weight": "bold"
                    };
                } else if (!status) {
                    o = {
                        color: "#bbb",
                        "font-weight": "bold"
                    };
                } else {
                    o = {
                        color: "#e89531",
                        "font-weight": "bold"
                    };
                }
                return o;
            }
        },
        check: {
            enable: true,
            chkboxType: {
                "Y": "s",
                "N": "ps"
            }
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: chooseRoleTreeStatus,
            beforeClick: function (event, treeId, treeNode) {
                return false;
            }
        }
    };

    ztree_role = $.fn.zTree.init($("#roleTree"), setting, zNodes);
}

function initFunc(data, status) {
    var zNodes = data;
    if (isFirst) {
        for (var i = zNodes.length - 1; i >= 0; i--) {
            var z = zNodes[i];
            if (z.type == "func") {
                z.name = '<i class="iconfont icon-jihuabaobiao"></i> ' + z.name;
            }
        }
    }
    var setting = {
        view: {
            showIcon: false,
            nameIsHTML: true,
            showTitle: false,
            showLine: false,
            addDiyDom: addDiyDom,
            fontCss: function (treeId, treeNode) {
                var o = {};
                if (treeNode.highlight) {
                    o = {
                        color: "red",
                        "font-weight": "bold"
                    };
                } else if (!status) {
                    o = {
                        color: "#bbb",
                        "font-weight": "bold"
                    };
                } else {
                    o = {
                        color: "#32b5cb",
                        "font-weight": "bold"
                    };
                }
                return o;
            }
        },
        check: {
            enable: true,
            chkboxType: {
                "Y": "",
                "N": ""
            }
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: funcOnCheck,
            beforeClick: function (event, treeId, treeNode) {
                return false;
            }
        }
    };

    ztree_func = $.fn.zTree.init($("#funcTree"), setting, zNodes);
}

function addDiyDom(treeId, treeNode) {
    var _o = $("#" + treeNode.tId);

    var str = '<div class="oper-box">';
    str += '<label><input type="checkbox" name="add" tId="@tId" id="add_@id">新增</label>';
    str += '<label><input type="checkbox" name="modify" tId="@tId" id="modify_@id">修改</label>';
    str += '<label><input type="checkbox" name="delete" tId="@tId" id="delete_@id">删除</label>';
    str += '<label><input type="checkbox" name="upload" tId="@tId" id="upload_@id">导入</label>';
    str += '<label><input type="checkbox" name="download" tId="@tId" id="download_@id">导出</label>';
    str += '</div>';

    str = str.replace(/@tId/g, treeNode.tId);
    str = str.replace(/@id/g, treeNode.id);
    _o.append(str);
}

function funcOnCheck(event, treeId, treeNode) {
    var tId = treeNode.tId;
    if (treeNode.checked) {
        $('input[tId=' + tId + ']').prop("checked", true);
    } else {
        $('input[tId=' + tId + ']').prop("checked", false);
    }

    chooseFuncTreeStatus(treeNode);
}

function addSave() {
    //查看模式不能保存
    if ($("#viewMode").prop("checked")) {
        return;
    }

    //判空
    var user_nodes = ztree_user.getCheckedNodes(true);
    var role_nodes = ztree_role.getCheckedNodes(true);
    var func_nodes = ztree_func.getCheckedNodes(true);
    //拼接参数
    var uId = [],
        uName = [],
        jId = [],
        jName = [],
        fId = [],
        fName = [];
    for (var i = user_nodes.length - 1; i >= 0; i--) {
        var u = user_nodes[i];
        if (u.type == "user") {
            uId.push(u.id);
            uName.push(u.name);
        }
    }

    for (var i = role_nodes.length - 1; i >= 0; i--) {
        var j = role_nodes[i];
        if (j.type == "role") {
            jId.push(j.id);
            jName.push(j.name);
        }
    }

    for (var i = func_nodes.length - 1; i >= 0; i--) {
        var f = func_nodes[i];
        if (f.type == "func") {
            var id = f.id;
            var flagAdd = $("#add_" + id).is(":checked");
            var flagModify = $("#modify_" + id).is(":checked");
            var flagDelete = $("#delete_" + id).is(":checked");
            var flagUpload = $("#upload_" + id).is(":checked");
            var flagDownload = $("#download_" + id).is(":checked");
            id += "," + flagAdd;
            id += "," + flagModify;
            id += "," + flagDelete;
            id += "," + flagUpload;
            id += "," + flagDownload;
            fId.push(id);
            fName.push(f.name);
        }
    }

    var countNull = 0;
    if (uId.length == 0) {
        countNull++;
    }
    if (jId.length == 0) {
        countNull++;
    }
    if (fId.length == 0) {
        countNull++;
    }
    if (countNull > 1) {
        return;
    }
    if (fId.length == 0 && func_nodes.length > 0) { //选中空文件夹
        alert("空文件夹不能进行赋权！");
        return;
    }

    uId = uId.join(";");
    uName = uName.join("　");
    jId = jId.join(";");
    jName = jName.join("　");
    fId = fId.join(";");
    fName = fName.join("　");

    var data = {
        "users": uId,
        "roles": jId,
        "funcs": fId,
    };

    var cntStr = '确认是否保存以下应用权限：<br/>';
    if (uName != '') {
        if (jName != '') { //功能可能为空
            cntStr += '<br/><label>保存用户与角色对应关系：</label><br/>';
            cntStr += uName + " <-----> " + jName + "<br/>";
            if (fName != '') { //三者都不为空，保存user和role，role和func，不保存user和func
                cntStr += '<br/><label>保存角色与功能对应关系：</label><br/>';
                cntStr += jName + " <-----> " + fName + "<br/>";
            }
        } else if (fName != '') { //只有角色为空
            cntStr += '<br/><label>保存用户与功能对应关系：</label><br/>';
            cntStr += uName + " <-----> " + fName + "<br/>";
        }
    } else if (jName != '' && fName != '') { //只有用户为空
        cntStr += '<br/><label>保存角色与功能对应关系：</label><br/>';
        cntStr += jName + " <-----> " + fName + "<br/>";
    }

    BootstrapDialog.confirm({
        title: '新增权限',
        message: cntStr,
        type: BootstrapDialog.TYPE_PRIMARY,
        closable: true,
        draggable: true,
        btnCancelLabel: '取消',
        btnOKLabel: '确定',
        btnOKClass: 'btn-primary',
        callback: function (result) {
            if (result) {
                addSubmit(data);
            } else {

            }
        }
    });
}

function addSubmit(data) {
    var url = '/manage/auth/add';
    Base.ajax({
        url: url,
        data: data,
        loadingCommit: true,
        success: function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("新增成功！");
            } else {
                tiperror("新增失败！");
            }
        }
    });
}


function deleteSave() {
    //查看模式不能删除
    if ($("#viewMode").prop("checked")) {
        return;
    }

    //判空
    var user_nodes = ztree_user.getCheckedNodes(true);
    var role_nodes = ztree_role.getCheckedNodes(true);
    var func_nodes = ztree_func.getCheckedNodes(true);
    //拼接参数
    var uId = [],
        uName = [],
        jId = [],
        jName = [],
        fId = [],
        fName = [];
    for (var i = user_nodes.length - 1; i >= 0; i--) {
        var u = user_nodes[i];
        if (u.type == "user") {
            uId.push(u.id);
            uName.push(u.name);
        }
    }

    for (var i = role_nodes.length - 1; i >= 0; i--) {
        var j = role_nodes[i];
        if (j.type == "role") {
            jId.push(j.id);
            jName.push(j.name);
        }
    }

    for (var i = func_nodes.length - 1; i >= 0; i--) {
        var f = func_nodes[i];
        if (f.type == "func") {
            var id = f.id;
            fId.push(id);
            fName.push(f.name);
        }
    }

    var countNull = 0;
    if (uId.length == 0) {
        countNull++;
    }
    if (jId.length == 0) {
        countNull++;
    }
    if (fId.length == 0) {
        countNull++;
    }
    if (countNull > 1) {
        return;
    }
    if (fId.length == 0 && func_nodes.length > 0) { //选中空文件夹
        alert("空文件夹不能进行赋权！");
        return;
    }

    uId = uId.join(";");
    uName = uName.join("　");
    jId = jId.join(";");
    jName = jName.join("　");
    fId = fId.join(";");
    fName = fName.join("　");

    var data = {
        "users": uId,
        "roles": jId,
        "funcs": fId,
    };

    var cntStr = '确认是否删除以下应用权限：<br/>';
    if (uName != '') {
        if (jName != '') { //功能可能为空
            cntStr += '<br/><label>删除用户与角色对应关系：</label><br/>';
            cntStr += uName + " <-----> " + jName + "<br/>";
            if (fName != '') { //三者都不为空，删除user和role，role和func，不删除user和func
                cntStr += '<br/><label>删除角色与功能对应关系：</label><br/>';
                cntStr += jName + " <-----> " + fName + "<br/>";
            }
        } else if (fName != '') { //只有角色为空
            cntStr += '<br/><label>删除用户与功能对应关系：</label><br/>';
            cntStr += uName + " <-----> " + fName + "<br/>";
        }
    } else if (jName != '' && fName != '') { //只有用户为空
        cntStr += '<br/><label>删除角色与功能对应关系：</label><br/>';
        cntStr += jName + " <-----> " + fName + "<br/>";
    }

    BootstrapDialog.confirm({
        title: '删除权限',
        message: cntStr,
        type: BootstrapDialog.TYPE_DANGER,
        closable: true,
        draggable: true,
        btnCancelLabel: '取消',
        btnOKLabel: '确定',
        btnOKClass: 'btn-danger',
        callback: function (result) {
            if (result) {
                deleteSubmit(data);
            } else {

            }
        }
    });
}

function deleteSubmit(data) {
    var url = '/manage/auth/delete';
    Base.ajax({
        url: url,
        data: data,
        loadingCommit: true,
        success: function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("删除成功！");
            } else {
                tiperror("删除失败！");
            }
        }
    });
}

/**
 * 非查看模式下，点击用户树事件
 * @return {[type]} [description]
 */
function chooseUserTreeStatus(treeNode) {
    var tId = treeNode.tId;
    if (!userStatus) {
        userStatus = true;
        initUser(userTreeData, userStatus);
        var node = ztree_user.getNodeByTId(tId);
        setCheckForNode(node, ztree_user);
    }
    var user_nodes = ztree_user.getCheckedNodes(true);
    var func_nodes = ztree_func.getCheckedNodes(true);
    var role_nodes = ztree_role.getCheckedNodes(true);

    if (role_nodes.length > 0) { //给角色赋权状态下
        if (user_nodes.length > 0 && funcStatus) { //第一次点击用户树节点时,置灰
            funcStatus = false;
            initFunc(funcTreeData, funcStatus);
        } else if (user_nodes.length == 0 && !funcStatus) { //恢复正常
            funcStatus = true;
            initFunc(funcTreeData, funcStatus);
        }
    } else if (func_nodes.length > 0) { //给功能赋权状态，角色树重新生成并置灰
        if (user_nodes.length > 0 && roleStatus) { //第一次点击用户树节点时,置灰
            roleStatus = false;
            initRole(roleTreeData, roleStatus);
        } else if (user_nodes.length == 0 && !roleStatus) { //恢复正常
            roleStatus = true;
            initRole(roleTreeData, roleStatus);
        }
    }
}

/**
 * 非查看模式下，点击角色树事件
 * @return {[type]} [description]
 */
function chooseRoleTreeStatus(treeNode) {
    var tId = treeNode.tId;
    if (!roleStatus) {
        roleStatus = true;
        initRole(roleTreeData, roleStatus);
        var node = ztree_role.getNodeByTId(tId);
        setCheckForNode(node, ztree_role);
    }
    var user_nodes = ztree_user.getCheckedNodes(true);
    var func_nodes = ztree_func.getCheckedNodes(true);
    var role_nodes = ztree_role.getCheckedNodes(true);
    if (user_nodes.length > 0) { //不允许自身树再响应点击事件
        if (role_nodes.length > 0 && funcStatus) { //第一次点击角色树节点时,置灰功能
            funcStatus = false;
            initFunc(funcTreeData, funcStatus);
        } else if (role_nodes.length == 0 && !funcStatus) { //恢复正常
            funcStatus = true;
            initFunc(funcTreeData, funcStatus);
        }
    } else if (func_nodes.length > 0) { //给功能赋权状态
        if (role_nodes.length > 0 && userStatus) { //第一次点击角色树节点时,置灰用户树
            userStatus = false;
            initUser(userTreeData, userStatus);
        } else if (role_nodes.length == 0 && !userStatus) { //恢复正常
            userStatus = true;
            initUser(userTreeData, userStatus);
        }
    }
}

/**
 * 非查看模式下，点击功能树事件
 * @return {[type]} [description]
 */
function chooseFuncTreeStatus(treeNode) {
    var tId = treeNode.tId;
    if (!funcStatus) {
        funcStatus = true;
        initFunc(funcTreeData, funcStatus);
        var node = ztree_func.getNodeByTId(tId);
        setCheckForNode(node, ztree_func);
    }
    var user_nodes = ztree_user.getCheckedNodes(true);
    var func_nodes = ztree_func.getCheckedNodes(true);
    var role_nodes = ztree_role.getCheckedNodes(true);
    if (user_nodes.length > 0) { //不允许自身树再响应点击事件
        if (func_nodes.length > 0 && roleStatus) { //第一次点击功能树节点时,置灰角色
            roleStatus = false;
            initRole(roleTreeData, roleStatus);
        } else if (func_nodes.length == 0 && !roleStatus) { //恢复正常
            roleStatus = true;
            initRole(roleTreeData, roleStatus);
        }
    } else if (role_nodes.length > 0) { //给功能赋权状态
        if (func_nodes.length > 0 && userStatus) { //第一次点击角色树节点时,置灰用户树
            userStatus = false;
            initUser(userTreeData, userStatus);
        } else if (func_nodes.length == 0 && !userStatus) { //恢复正常
            userStatus = true;
            initUser(userTreeData, userStatus);
        }
    }
}

function resetAllTree() {
    userStatus = true;
    roleStatus = true;
    funcStatus = true;
    initUser(userTreeData, userStatus);
    initRole(roleTreeData, roleStatus);
    initFunc(funcTreeData, funcStatus);
}

function userSearch() {
    var s = $("#userSearchInput").val();
    s = $.trim(s);

    ztree_user.expandAll(true);

    if (s.length > 0) {
        var nodes = ztree_user.getNodesByFilter(function (node) {
            var id = node.id;
            var name = node.name;
            var type = node.type;
            return ((id.indexOf(s) != -1 || name.indexOf(s) != -1) && "user" == type);
        });
        var selNodes = [];
        for (var i = nodes.length - 1; i >= 0; i--) {
            var node = nodes[i];
            selNodes = selNodes.concat(node.getPath());
        }
        ztree_user.hideNodes(ztree_user.getNodes());
        ztree_user.showNodes(selNodes); // BUG，因为showNodes会显示所有兄弟节点，导致会显示非匹配的兄弟节点

    } else {
        ztree_user.showNodes(ztree_user.getNodes());
    }
}

function roleSearch() {
    var s = $("#roleSearchInput").val();
    s = $.trim(s);

    ztree_role.expandAll(true);

    if (s.length > 0) {
        var nodes = ztree_role.getNodesByFilter(function (node) {
            var id = node.id;
            var name = node.name;
            var type = node.type;
            return ((id.indexOf(s) != -1 || name.indexOf(s) != -1) && "role" == type);
        });
        var selNodes = [];
        for (var i = nodes.length - 1; i >= 0; i--) {
            var node = nodes[i];
            selNodes = selNodes.concat(node.getPath());
        }
        ztree_role.hideNodes(ztree_role.getNodes());
        ztree_role.showNodes(selNodes); // BUG，因为showNodes会显示所有兄弟节点，导致会显示非匹配的兄弟节点
    } else {
        ztree_role.showNodes(ztree_role.getNodes());
    }
}

function funcSearch() {
    var s = $("#funcSearchInput").val();
    s = $.trim(s);

    ztree_func.expandAll(true);

    if (s.length > 0) {
        var nodes = ztree_func.getNodesByFilter(function (node) {
            var id = node.id;
            var name = node.name;
            var type = node.type;
            return ((id.indexOf(s) != -1 || name.indexOf(s) != -1) && "func" == type);
        });
        var selNodes = [];
        for (var i = nodes.length - 1; i >= 0; i--) {
            var node = nodes[i];
            selNodes = selNodes.concat(node.getPath());
        }
        ztree_func.hideNodes(ztree_func.getNodes());
        ztree_func.showNodes(selNodes); // BUG，因为showNodes会显示所有兄弟节点，导致会显示非匹配的兄弟节点
    } else {
        ztree_func.showNodes(ztree_func.getNodes());
    }
}